import { Component, DestroyRef, inject, OnInit } from '@angular/core';
import { AbstractControl, FormControl, FormGroup, ReactiveFormsModule, ValidatorFn, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { SheQu } from '../../models/shequ.model';
import { ShequService } from '../../services/shequ.service';

@Component({
  selector: 'app-shequ-detail',
  imports: [ReactiveFormsModule],
  templateUrl: './shequ-detail.component.html',
  styleUrl: './shequ-detail.component.css'
})
export class SheQuDetailComponent implements OnInit {
  private activatedRoute = inject(ActivatedRoute);
  private router = inject(Router);
  private destroyRef = inject(DestroyRef);
  private shequService = inject(ShequService);
  private isCreate = false;

  form = new FormGroup({
    sheQuID: new FormControl<string | null>(null),
    mingCheng: new FormControl<string>('', {
      validators: [Validators.required]
    }),
    dianHua: new FormControl<string | null>(null),
    shuJi: new FormControl<string | null>(null),
    shuJiDianHua: new FormControl<string | null>(null, {
      validators: [phoneNumberValidator]
    })
  });


  ngOnInit(): void {
    // 这里使用了ActivatedRoute的data属性来获取路由解析的数据，判断是创建还是编辑社区
    const subscription = this.activatedRoute.data.subscribe(data => {
      if (data['httpMethod'] === 'POST') {//创建社区
        this.isCreate = true;
        this.form.reset();
      } else if (data['httpMethod'] === 'PUT') {//编辑社区
        //从路由中的id参数获取社区对象
        let shequID = this.activatedRoute.snapshot.paramMap.get('id');
        let editSheQu = this.shequService.allSheQu().find(item => item.sheQuID == shequID);//两个id类型不一致，需要用==进行字面值判断
        //填充表单
        this.form.controls.sheQuID.setValue(editSheQu?.sheQuID ? editSheQu?.sheQuID : null);
        this.form.controls.mingCheng.setValue(editSheQu?.mingCheng!);
        this.form.controls.dianHua.setValue(editSheQu?.dianHua ? editSheQu?.dianHua : null);
        this.form.controls.shuJi.setValue(editSheQu?.shuJi ? editSheQu?.shuJi : null);
        this.form.controls.shuJiDianHua.setValue(editSheQu?.shuJiDianHua ? editSheQu?.shuJiDianHua : null);
      }
    });

    this.destroyRef.onDestroy(() => subscription.unsubscribe());
  }

  onSubmit() {
    if (this.form.invalid) {
      return;
    }
    //判断社区名称是否已存在
    let sameMingChengSheQu = this.shequService.allSheQu().find(item => item.mingCheng === this.form.value.mingCheng);
    if (sameMingChengSheQu && sameMingChengSheQu.sheQuID !== this.form.value.sheQuID) {
      // 说明社区名称已存在
      this.form.controls.mingCheng.setErrors({ alreadyExists: true });
      return;
    }

    let postSheQu: SheQu = {//将所有是数据保存为字符串格式，后端才能进行正确解析
      sheQuID: this.form.value.sheQuID?.toString(),
      mingCheng: this.form.value.mingCheng?.toString(),
      dianHua: this.form.value.dianHua?.toString(),
      shuJi: this.form.value.shuJi?.toString(),
      shuJiDianHua: this.form.value.shuJiDianHua?.toString()
    };

    if (this.isCreate) {
      //创建社区
      const subscription = this.shequService.createSheQu(postSheQu).subscribe({
        next: (data: SheQu) => {
          console.log('创建成功');
        },
        error: (err: Error) => {
          console.error('创建失败', err);
        },
        complete: () => { this.router.navigate(['/shequ']); }
      });
      this.destroyRef.onDestroy(() => subscription.unsubscribe());
    } else {
      //编辑社区
      const subscription = this.shequService.updateSheQu(postSheQu).subscribe({
        next: (data: SheQu) => {
          console.log('更新成功');
        },
        error: (err: Error) => {
          console.error('更新失败', err);
        },
        complete: () => { this.router.navigate(['/shequ']); }
      });
      this.destroyRef.onDestroy(() => subscription.unsubscribe());
    }
  }

  onCancel() {
    this.form.reset();
    this.router.navigate(['/shequ']);
  }

}

export function phoneNumberValidator(control: AbstractControl): ValidatorFn | null {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const phoneNumber = control.value;
    if (phoneNumber === null || phoneNumber === undefined) {
      return null;
    }
    const isValid = vaildPhoneNumber(phoneNumber ? phoneNumber.toString() : '');
    return isValid ? null : { invalidPhoneNumber: true };
  };
}

/**
 * @description: 验证手机号正确性
 * @param {string} phoneNumber 手机号
 * @return  {boolean} 是否验证通过  true|返回运营商-通过 false-不通过
 */
export function vaildPhoneNumber(phoneNumber: string): string | boolean {
  // 规则说明 2019-12-24 工信部核发190、192、196、197号段
  // 【虚拟运营商】：170[1700/1701/1702]、162(电信)，1703/1705/1706、165(移动)，1704/1707/1708/1709(联通)、171、167（联通）
  // 【卫星通信】： 1740[0-5] (电信)，1349(移动)
  // 【物联网网号】：10648、1440 (移动)，10646、146(联通)，10649、1410(电信)
  // 【国家工信部应急通信】：1740[6-9]，1741[0-2]

  // 所以整理分类号段
  // 手机号码: 13[0-9], 14[5,6,7,8,9], 15[0-3, 5-9], 16[2,5,6,7], 17[0-8], 18[0-9], 19[0-3, 5-9]
  // 移动号段: 13[4-9],147,148,15[0-2,7-9],165,170[3,5,6],172,178,18[2-4,7-8],19[5,7,8]
  // 联通号段: 130,131,132,145,146,155,156,166,167,170[4,7,8,9],171,175,176,185,186,196
  // 电信号段: 133,149,153,162,170[0,1,2],173,174[0-5],177,180,181,189,19[0,1,3,9]
  // 广电号段: 192
  const regMOBILE = /^(13[0-9]|14[5-9]|15[0-3,5-9]|16[2,5,6,7]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;
  const regCNMobilE = /^((13[4-9])|(14[7-8])|(15[0-2,7-9])|(165)|(178)|(18[2-4,7-8])|(19[5,7,8]))\d{8}|(170[3,5,6])\d{7}$/;
  const regCNUnicom = /^((13[0-2])|(14[5,6])|(15[5-6])|(16[6-7])|(17[1,5,6])|(18[5,6])|(196))\d{8}|(170[4,7-9])\d{7}$/;
  const regCNTelecom = /^((133)|(149)|(153)|(162)|(17[3,7])|(18[0,1,9])|(19[0,1,3,9]))\d{8}|((170[0-2])|(174[0-5]))\d{7}$/;
  const regCNBroadcastingNetwork = /^((192))\\d{8}$/;

  if (regCNMobilE.test(phoneNumber)) return '中国移动';

  if (regCNUnicom.test(phoneNumber)) return '中国联通';

  if (regCNTelecom.test(phoneNumber)) return '中国电信';

  if (regCNBroadcastingNetwork.test(phoneNumber)) return '中国广电';

  if (regMOBILE.test(phoneNumber)) return true;

  return false;
};

